package com.yingsheng.bi.hks.repository.dao.service;

import com.yingsheng.bi.hks.basic.utils.Utils;
import com.yingsheng.bi.hks.repository.dao.mapper.AddressMapper;
import com.yingsheng.bi.hks.repository.dao.po.Address;
import com.yingsheng.bi.hks.repository.dao.po.AddressExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

/**
 * merchants表的数据库操作服务
 * 要求说明：
 * 1.一般情况下,要求参数不超过5个时方法入参逐个声明
 * 2.一般情况下,要求条件不超过3个时要在方法名上体现
 * 3.最好对方法入参做一定校验,尤其是对条件参数至少要做非空校验
 *
 * @author 83686
 */
@Repository
public class AddressDaoService implements DaoService {

    @Autowired
    private AddressMapper addressMapper;

    public boolean insert(Address address) {
        if (address.getDefaultFlg() == 0) {
            clearDefaultFlg(address.getUserId(),address.getType());
        }
        address.setId(Utils.genUUid());
        int result = addressMapper.insert(address);
        return result == 1;
    }

    public boolean updateByAddrId(Address address) {
        if (address.getDefaultFlg() == 0) {
            clearDefaultFlg(address.getUserId(),address.getType());
        }
        address.setUpdateTime(new Date());
        int result = addressMapper.updateByPrimaryKeySelective(address);
        return result == 1;
    }

    public List<Address> query(String userId,String type){
        AddressExample example = new AddressExample();
        example.createCriteria().andUserIdEqualTo(userId).andTypeEqualTo(type);
        return addressMapper.selectByExample(example);
    }

    public boolean del(String addrId){
        return addressMapper.deleteByPrimaryKey(addrId) == 1;
    }

    private void clearDefaultFlg(String userId,String type){
        Address address = new Address();
        address.setDefaultFlg(1);
        AddressExample example = new AddressExample();
        example.createCriteria().andUserIdEqualTo(userId).andTypeEqualTo(type);
        addressMapper.updateByExampleSelective(address, example);
    }

}
